<template>
  <div>
    <!-- 顶部导航栏 -->
    <header class="exchange-header">
      <a href="#" class="exchange-logo">
        <i class="fas fa-chart-line mr-2"></i>
        区块链证券交易所
      </a>
      
      <div class="user-info">
        <div class="user-avatar">
          <i class="fas fa-user"></i>
        </div>
        <span class="user-name">{{ user?.username }}</span>
        <span class="user-role badge badge-warning">{{ user?.role }}</span>
        <span class="wallet-address ml-3">{{ shortenAddress(user?.eoaAddress) }}</span>
        
        <button class="btn btn-sm btn-outline-light ml-3" @click="handleLogout">
          <i class="fas fa-sign-out-alt"></i>
        </button>
      </div>
    </header>

    <!-- 侧边栏 -->
    <aside class="exchange-sidebar">
      <div class="sidebar-sticky">
        <div class="sidebar-heading">主要导航</div>
        <ul class="sidebar-nav">
          <li class="sidebar-nav-item">
            <router-link to="/" class="sidebar-nav-link">
              <i class="fas fa-home"></i>
              <span>首页</span>
            </router-link>
          </li>
          <li class="sidebar-nav-item">
            <router-link to="/user" class="sidebar-nav-link">
              <i class="fas fa-wallet"></i>
              <span>我的资产</span>
            </router-link>
          </li>
          <li class="sidebar-nav-item">
            <router-link to="/admin" class="sidebar-nav-link active">
              <i class="fas fa-chart-bar"></i>
              <span>股票管理</span>
            </router-link>
          </li>
        </ul>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="exchange-content">
      <div v-if="systemMessage" class="alert" :class="systemMessage.type" style="margin-bottom: 20px;">
        {{ systemMessage.text }}
      </div>
      
      <h1 class="h3 mb-4">股票管理</h1>
      
      <div class="alert alert-info">
        <i class="fas fa-info-circle mr-2"></i>
        <strong>提示：</strong>所有用户都可以创建股票。只有完全拥有股票的用户才能编辑或删除该股票。
      </div>
      
      <div class="row">
        <!-- 股票列表 -->
        <div class="col-12 col-lg-6 mb-4">
          <div class="exchange-card">
            <div class="exchange-card-header">
              <h5 class="exchange-card-title">
                <i class="fas fa-list mr-2"></i>股票列表
              </h5>
              <button class="btn btn-sm btn-outline-primary" @click="loadStockList">
                <i class="fas fa-sync-alt mr-1"></i>刷新
              </button>
            </div>
            <div class="exchange-card-body p-0">
              <div v-if="loading" class="text-center py-4">
                <div class="loading-spinner mx-auto"></div>
              </div>
              
              <div v-else-if="stocks.length === 0" class="text-center py-4">
                <p class="text-muted">暂无股票</p>
              </div>
              
              <div v-else class="table-responsive">
                <table class="table stock-table mb-0">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>名称</th>
                      <th>总股本</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="stock in stocks" :key="stock.stockId">
                      <td><span class="badge badge-primary">{{ stock.stockId }}</span></td>
                      <td>{{ stock.name }}</td>
                      <td>{{ formatNumber(stock.totalShares) }}</td>
                      <td>
                        <button 
                          class="btn btn-sm btn-info mr-1" 
                          @click="viewStockDetails(stock.stockId)"
                          title="查看详情"
                        >
                          <i class="fas fa-eye"></i>
                        </button>
                        <button 
                          class="btn btn-sm btn-warning mr-1" 
                          @click="editStock(stock)"
                          title="编辑（需完全拥有）"
                        >
                          <i class="fas fa-edit"></i>
                        </button>
                        <button 
                          class="btn btn-sm btn-danger" 
                          @click="deleteStock(stock.stockId)"
                          title="删除（需完全拥有）"
                        >
                          <i class="fas fa-trash"></i>
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 添加股票表单 -->
        <div class="col-12 col-lg-6 mb-4">
          <div class="exchange-card">
            <div class="exchange-card-header">
              <h5 class="exchange-card-title">
                <i class="fas fa-plus mr-2"></i>{{ isEditing ? '编辑股票' : '添加股票' }}
              </h5>
              <button v-if="isEditing" class="btn btn-sm btn-secondary" @click="cancelEdit">
                取消编辑
              </button>
            </div>
            <div class="exchange-card-body">
              <form @submit.prevent="handleAddStock">
                <div class="form-group">
                  <label>股票名称</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="stockForm.name"
                    placeholder="例如：苹果公司"
                    required
                  />
                </div>
                
                <div class="form-group">
                  <label>股票描述</label>
                  <textarea 
                    class="form-control" 
                    v-model="stockForm.description"
                    placeholder="股票详细描述"
                    rows="3"
                    required
                  ></textarea>
                </div>
                
                <div class="form-group">
                  <label>总股本</label>
                  <input 
                    type="number" 
                    class="form-control" 
                    v-model.number="stockForm.totalShares"
                    placeholder="1000000"
                    min="1"
                    required
                  />
                </div>
                
                <button 
                  type="submit" 
                  class="btn btn-primary btn-block" 
                  :disabled="submitting"
                >
                  <span v-if="submitting">
                    <i class="fas fa-spinner fa-spin mr-2"></i>处理中...
                  </span>
                  <span v-else>
                    <i :class="isEditing ? 'fas fa-save' : 'fas fa-plus'" class="mr-2"></i>
                    {{ isEditing ? '更新股票（需完全拥有）' : '创建股票' }}
                  </span>
                </button>
              </form>
            </div>
          </div>
        </div>
        
        <!-- 股票详情模态框 -->
        <div v-if="selectedStock" class="col-12">
          <div class="exchange-card">
            <div class="exchange-card-header">
              <h5 class="exchange-card-title">
                <i class="fas fa-info-circle mr-2"></i>股票详情 - {{ selectedStock.name }}
              </h5>
              <button class="btn btn-sm btn-secondary" @click="selectedStock = null">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <div class="exchange-card-body">
              <div class="row mb-3">
                <div class="col-md-6">
                  <p><strong>股票ID:</strong> {{ selectedStock.stockId }}</p>
                  <p><strong>股票名称:</strong> {{ selectedStock.name }}</p>
                  <p><strong>描述:</strong> {{ selectedStock.description }}</p>
                </div>
                <div class="col-md-6">
                  <p><strong>总股本:</strong> {{ formatNumber(selectedStock.totalShares) }}</p>
                  <p><strong>股东数量:</strong> {{ selectedStock.shareholderList?.length || 0 }}</p>
                  <p><strong>创建时间:</strong> {{ formatDate(selectedStock.timestamp) }}</p>
                </div>
              </div>
              
              <h6><i class="fas fa-users mr-2"></i>股东列表</h6>
              <div v-if="loadingDetails" class="text-center py-3">
                <div class="loading-spinner mx-auto"></div>
              </div>
              <table v-else-if="stockDetails.addresses?.length > 0" class="table table-sm">
                <thead>
                  <tr>
                    <th>地址</th>
                    <th>持股数量</th>
                    <th>持股比例</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(address, index) in stockDetails.addresses" :key="address">
                    <td><code>{{ address }}</code></td>
                    <td>{{ formatNumber(stockDetails.shares[index]) }}</td>
                    <td>{{ ((stockDetails.shares[index] / selectedStock.totalShares) * 100).toFixed(2) }}%</td>
                  </tr>
                </tbody>
              </table>
              <p v-else class="text-muted">暂无股东</p>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useContractStore } from '@/stores/contract'

const router = useRouter()
const authStore = useAuthStore()
const contractStore = useContractStore()

const user = computed(() => authStore.user)
const isContractOwner = computed(() => contractStore.isContractOwner())

const stocks = ref([])
const selectedStock = ref(null)
const stockDetails = ref({})
const loading = ref(true)
const loadingDetails = ref(false)
const submitting = ref(false)
const systemMessage = ref(null)
const isEditing = ref(false)

const stockForm = ref({
  stockId: null,
  name: '',
  description: '',
  totalShares: ''
})

const shortenAddress = (address) => {
  if (!address) return ''
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num)
}

const formatDate = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp * 1000).toLocaleString('zh-CN')
}

const showMessage = (text, type = 'alert-info') => {
  systemMessage.value = { text, type }
  setTimeout(() => {
    systemMessage.value = null
  }, 5000)
}

const loadStockList = async () => {
  loading.value = true
  try {
    const nextId = await contractStore.getNextStockId()
    console.log('总股票数:', nextId)
    const stocksList = []
    
    for (let i = 0; i < nextId; i++) {
      try {
        const stock = await contractStore.getStock(i)
        console.log(`股票 ${i}:`, stock)
        if (stock.timestamp > 0) {
          stocksList.push(stock)
        }
      } catch (error) {
        console.log(`股票 ${i} 不存在或已被删除:`, error.message)
      }
    }
    
    console.log('成功加载股票列表:', stocksList)
    stocks.value = stocksList
  } catch (error) {
    console.error('加载股票列表失败:', error)
    showMessage('加载股票列表失败: ' + error.message, 'alert-danger')
  } finally {
    loading.value = false
  }
}

const viewStockDetails = async (stockId) => {
  loadingDetails.value = true
  try {
    const stock = await contractStore.getStock(stockId)
    selectedStock.value = stock
    
    const details = await contractStore.getAllShareholders(stockId)
    stockDetails.value = details
  } catch (error) {
    console.error('加载股票详情失败:', error)
    showMessage('加载股票详情失败', 'alert-danger')
  } finally {
    loadingDetails.value = false
  }
}

const editStock = (stock) => {
  isEditing.value = true
  stockForm.value = {
    stockId: stock.stockId,
    name: stock.name,
    description: stock.description,
    totalShares: stock.totalShares
  }
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const cancelEdit = () => {
  isEditing.value = false
  stockForm.value = {
    stockId: null,
    name: '',
    description: '',
    totalShares: ''
  }
}

const handleAddStock = async () => {
  submitting.value = true
  try {
    if (isEditing.value) {
      // 更新股票
      await contractStore.updateStock(
        stockForm.value.stockId,
        stockForm.value.name,
        stockForm.value.description,
        stockForm.value.totalShares
      )
      showMessage('股票更新成功！', 'alert-success')
      cancelEdit()
    } else {
      // 添加股票
      await contractStore.addStock(
        stockForm.value.name,
        stockForm.value.description,
        stockForm.value.totalShares
      )
      showMessage('股票添加成功！', 'alert-success')
      stockForm.value = {
        stockId: null,
        name: '',
        description: '',
        totalShares: ''
      }
    }
    
    await loadStockList()
  } catch (error) {
    console.error('操作失败:', error)
    showMessage('操作失败: ' + error.message, 'alert-danger')
  } finally {
    submitting.value = false
  }
}

const deleteStock = async (stockId) => {
  if (!confirm('确定要删除这个股票吗？只有完全拥有该股票才能删除！')) {
    return
  }
  
  try {
    await contractStore.removeStock(stockId)
    showMessage('股票删除成功！', 'alert-success')
    await loadStockList()
  } catch (error) {
    console.error('删除失败:', error)
    showMessage('删除失败: ' + error.message, 'alert-danger')
  }
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

onMounted(async () => {
  const connected = await contractStore.initProvider()
  if (connected) {
    // 检查账户是否匹配
    const userEoaAddress = user.value?.eoaAddress
    const metamaskAccount = contractStore.currentAccount
    
    if (userEoaAddress && metamaskAccount) {
      if (userEoaAddress.toLowerCase() !== metamaskAccount.toLowerCase()) {
        showMessage(
          `⚠️ 账户不匹配！当前登录：${shortenAddress(userEoaAddress)}，MetaMask：${shortenAddress(metamaskAccount)}。使用 MetaMask 账户进行操作。`, 
          'alert-warning'
        )
      }
    }
    
    await loadStockList()
  } else {
    showMessage('请连接 MetaMask 钱包', 'alert-warning')
    loading.value = false
  }
})
</script>

